<?php

App::uses('AppController', 'Controller');

class ProductsController extends AppController {

	var $name = 'Products';

	var $uses = array('Product');

	/**
	 * List product user
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function index()
	{
		$this->layout = 'user';
	}


	/**
	 * List product
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function admin_index() {

		// Get product
		$products = $this->Product->getAll();

		// Get category
		App::uses('Category', 'Model');
		$Category = new Category();
		$categories = $Category->getList();

		$this->set('products', $products);
		$this->set('categories', $categories);
	}

	/**
	 * Add
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function admin_add($id = null)
	{
		// Post
		if( !empty($this->request->data)) {

			App::uses('ProductImage', 'Model');
			$PM = new ProductImage();
			$data = &$this->request->data['Product'];
			$data['image'] = '';

			// Xoa image cu khi edit
			if( !empty( $data['images_old']) )
			{
				if( !empty($data['images_del']) ) {

					$imgolds = array_diff($data['images_old'], $data['images_del']);
					$this->_removeImages($PM, $data['images_del'] );

				} else {
					$imgolds = $data['images_old'];
				}

				unset($data['images_del']);
				unset($data['images_old']);
				$imgolds = array_values($imgolds);

				if(!empty($imgolds)){
					$data['image'] = $imgolds[0];
				}
			}

			// upload img
			$images = array();

			// Truong hop co upload hinh moi
			if(!empty($data['images']))
			{
				foreach($data['images'] as $img)
				{
					if(!empty( $img['name'] ) && $img['error'] == 0) {
						$images[] = $this->_upload($img);
					}
				}

				unset($data['images']);

				// Get default image
				if( !empty($images)) {
					$data['image'] = $images[0];
				}
			}

			// Kiem tra errors
			$this->Product->set($data);
			$errors = $this->Product->invalidFields();

			// Neu khong co loi thi tien hanh save
			if(empty($errors)) {

				// Kiem tra edit
				if(empty($data['id'])) {
					unset($data['id']);
				}

				// Get info
				$this->Common->get_common_info($data);

				if($this->Product->save($data, false)) {

					// save image
					$id = (int)$this->Product->id;

					foreach($images as $img) {
						$data = array(
							'product_id' => $id,
							'image' => $img
						);
						$PM->create();
						$PM->save($data);
					}

					$this->Session->setFlash('Save product success.', 'success');
					$this->redirect('/admin/products');
				} else {
					$this->Session->setFlash('Save product fail.', 'error');
				}
			} else {
				$this->Session->setFlash('Save product fail.', 'error');
				// delete image upload
				if( !empty($images)) {
					$this->request->data['Product']['image'] = '';

					foreach ($images as $img){
						$path1 = PUBLIC_IMAGE_THUMB.$img;
						$path2 = PUBLIC_IMAGE_DETAIL.$img;
						@unlink($path1 );
						@unlink($path2 );
					}
				}
			}
		}

		// Truong hop show edit
		if(!empty($id)) {

			$id = (int)$id;
			$info = $this->Product->getInfoById($id);
			$this->request->data = $info;

			App::uses('ProductImage', 'Model');
			$PM = new ProductImage();

			$images = $PM->getAllByPid($id);
			$this->set('images', $images);
		}

		// Get danh muc
		App::uses('Category', 'Model');
		$Category = new Category();
		$categories = $Category->getList();
		$this->set('categories', $categories);
	}


	/**
	 * Remove image
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function _removeImages ($PM, $data)
	{
		if(!empty($data)) {
			foreach($data as $it){

				if(!empty($it)) {

					$info = $PM->getInfoById((int)$it);

					$path = PUBLIC_IMAGE_DETAIL.$info['ProductImage']['image'];
					$path = PUBLIC_DETAIL_SHOW.$info['ProductImage']['image'];
					@unlink($path);

					$query = 'DELETE FROM product_images WHERE id = '.(int)$it;
					$PM->query($query);
				}
			}
		}

	}

	/**
	 * search product
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function search()
	{
        $items = array();
        $this->Product->alias = 'P';
        if(!empty( $_GET['q'] ))
        {
            $cond = array(
                'name LIKE' => '%'.trim($_GET['q']).'%',
                'status' => 4
            );

            if( !empty( $_GET['datanone'] ) ) {
            	$nin = explode(',', $_GET['datanone']);
            	array_pop($nin);

            	if(count($nin) > 0) {
            		$cond['id  !='] = $nin;
            	}
            }

            $items = $this->Product->find( 'all', array( 'conditions' => $cond ) );
        }

        $this->_responseJson( array( 'items' => $items ));
	}
}
